package controller.Actions;

import java.io.Serializable;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Erro;
import model.SearchAccount;
import model.User;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.json.JSONArray;
import org.json.JSONObject;

import dao.SearchAccountDAO;

public class SearchDescAccountAction  extends Action implements Serializable{

	final static Logger looger = Logger.getLogger(SearchDescAccountAction.class);
	  @Override
		public ActionForward execute(ActionMapping mapping,
	            ActionForm form,
	            HttpServletRequest request,
	            HttpServletResponse response) throws Exception {
	        try {

	            User u = (User) request.getSession().getAttribute("User");
	            if (u == null) {
	                request.getSession().setAttribute("ErroMSG", Erro.erroMsg[Erro.NAO_AUTENTICADO]);
	                return mapping.findForward("erroAlias");
	            } else {

	                SearchAccountDAO gpDAO = new SearchAccountDAO();

	                String key = request.getParameter("key");
	                
	                ArrayList<SearchAccount> listaContas = gpDAO.readKey(key);

	                JSONArray array = new JSONArray();
	                
	                for (SearchAccount sa : listaContas) {
	                	
	                    JSONObject object = new JSONObject();

	                    object.put("extendida", sa.getDescextendida());

	                    array.put(object);
	                }

	                String jsonResult = array.toString();
	                response.setContentType("text/javascript; charset=utf-8");
	                response.getWriter().write(jsonResult);
	                gpDAO.closeDAO();
              
	                

	                return null;
	            }

	        } catch (Exception e) {
	        	
	        	looger.error("Erro ao buscar descrição do plano de Contas " ,e);
	        	
	            return mapping.findForward("erroAlias");
	        }
	    }
}
